<?php

namespace App\Admin\Controllers;

use App\Models\InventoryFunc;
use App\Models\Purchasedetail;

//use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Layout\Content;
use App\Http\Controllers\Controller;
use Encore\Admin\Controllers\ModelForm;
use Encore\Admin\Widgets\Table;
use Encore\Admin\Widgets\Form as myForm;


class InsController extends Controller
{
    use ModelForm;

    /**
     * Index interface.
     *
     * @return Content
     */
    public function index()
    {
        return Admin::content(function (Content $content) {

            $content->header('入库管理');
            $content->description('Ins');

            $content->body($this->grid());
        });
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Admin::grid(Purchasedetail::class, function (Grid $grid) {
            $grid->model()->select('purchase_detail.*','purchase_detail.id as detail_id','company.name','supplier.name as supplier_name','warehouse.name as warehouse_name','purchase.*','admin_users.name as operater_name','sku.name as sku_name')
            ->leftjoin('purchase','purchase.id','=','purchase_detail.purchase_id')
            ->leftjoin('company','company.id','=','purchase.company_id')
            ->leftjoin('supplier','supplier.id','=','purchase.supplier_id')
            ->leftjoin('admin_users','admin_users.username','=','purchase.operater_id')
            ->leftjoin('sku','sku.id','=','purchase_detail.sku_id')
            ->leftjoin('warehouse','warehouse.id','=','purchase.warehouse_id')
            ->where('purchase.company_id',Admin::user()->company_id)
            ->orderBy('purchase.created_at', 'desc');
            $grid->purchase_id('采购单编号')->sortable();
            $grid->supplier_name('供应商名称');
            $grid->sku_name('SKU名称');
            $grid->name('所属公司');
            $grid->operater_name('采购员');
            $grid->arrive_time('到货时间');
            $grid->warehouse_name('仓库名称');
            $grid->in_state('入库状态')->display(function($v){
                return HelpersController::getStateValue('inState',$v);
            });
            $grid->review_state("审核状态")->display(function($v){
                return HelpersController::getStateValue('purchaseReviewState',$v);
            });
            // $grid->total_amount('含税金额')->display(function($v){return round($v,2);});
            // $grid->exchange_amount('汇率后含税价')->display(function($v){return round($v,2);});
            // $grid->tax('税额')->display(function($v){return round($v,2);});
            // $grid->exchange_rate('汇率')->display(function($v){return $v."%";});
            // $grid->rate('税率')->display(function($v){return $v."%";});
            //$grid->created_at('创建时间');
            //$grid->updated_at('更新时间');
            //$grid->bar_code('条形码url');
            // $grid->pay_type('付款方式');
            // $grid->pay_status('付款状态');
            // $grid->paid_amount('已付金额');
            //$grid->purchase_type('采购单类型');
            //$grid->remark('备注');
            $grid->disableCreateButton();//禁用新增按钮
            $grid->disableExport();//禁用导出按钮
            $grid->actions(function ($actions) {
                // append一个操作
                $actions->disableEdit();
                $actions->disableDelete();//禁用删除
                $actions->prepend('<a href="'.\Route('ins.show',['id'=>$actions->row['detail_id']]).'"><i class="fa fa-eye"></i></a>');
            });
            $grid->filter(function($filter){
                // 去掉默认的id过滤器
                $filter->disableIdFilter();

                $filter->where(function ($query) {
                    $query->where('purchase_detail.purchase_id', 'like', "%{$this->input}%");
                }, '采购单编号');

                $filter->where(function ($query) {
                    $query->where('supplier.name', 'like', "%{$this->input}%");
                }, '供应商名称');

                $filter->where(function ($query) {
                     $query->where('admin_users.name', 'like', "%{$this->input}%");
                }, '采购员');

                $filter->where(function ($query) {
                    $query->where('warehouse.name', 'like', "%{$this->input}%");
                }, '仓库名称');
            });
        });
    }

    public function show($id)
    {
        $data = \DB::table('purchase_detail')->select('admin_users.name as user_name','company.name as company_name','supplier.name as supplier_name','warehouse.name as warehouse_name','purchase.*','purchase_detail.*','sku.name as sku_name','batch_grade.name as batch_grade','batch_thick.name as batch_thick','batch_origin.name as batch_origin','batch_colour.name as batch_colour','batch_avg_size.name as batch_avg_size','batch_min_size.name as batch_min_size','reviewer.name as reviewer_name')
                        ->leftjoin('purchase','purchase.id','=','purchase_detail.purchase_id')
                        ->leftjoin('admin_users','admin_users.username','=','purchase.operater_id')
                        // ->leftjoin('admin_users as documentary','documentary.username','=','agent.merchandiser')
                        // ->leftjoin('admin_users as salesman','salesman.username','=','agent.salesman')
                        ->leftjoin('admin_users as reviewer','reviewer.username','=','purchase.reviewer_id')
                        ->leftjoin('company','company.id','=','purchase.company_id')
                        ->leftjoin('supplier','supplier.id','=','purchase.supplier_id')
                        ->leftjoin('warehouse','warehouse.id','=','purchase.warehouse_id')
                        ->leftjoin('sku','purchase_detail.sku_id','=','sku.id')
                        ->leftjoin('batchattribute as batch_grade','purchase_detail.grade','=','batch_grade.id')
                        ->leftjoin('batchattribute as batch_thick','purchase_detail.thick','=','batch_thick.id')
                        ->leftjoin('batchattribute as batch_origin','purchase_detail.origin','=','batch_origin.id')
                        ->leftjoin('batchattribute as  batch_colour','purchase_detail.colour','=','batch_colour.id')
                        ->leftjoin('batchattribute as batch_avg_size','purchase_detail.avg_size','=','batch_avg_size.id')
                        ->leftjoin('batchattribute as batch_min_size','purchase_detail.min_size','=','batch_min_size.id')
                        ->where('purchase_detail.id',$id)->first();
        // dd($data);
        $content = '<div style="width:80%;margin:0 auto;background:#fff;padding:10px;"><h4 style="text-align:center;">基本信息</h4><hr>';
        $headers = [];
        $rows = [
            ['采购单编号', $data->purchase_id,'合同订单编号', $data->contract_id],
            ['订单类型', HelpersController::getStateValue('inType',$data->type),'供应商编号', $data->supplier_name],
            ['所属公司', $data->company_name],
        ];
        $table_1 = new Table($headers, $rows);
        $content .= $table_1->render();

        $content .= '<h4 style="text-align:center;">系统信息</h4><hr>';

        // table 2
        $headers = [];
        $rows = [
            ['操作人',$data->user_name,'订单状态', HelpersController::getStateValue('purchaseState',$data->type)],
            // ['销售',isset($data->salesman)?$data->salesman:'未维护该客户销售','跟单', isset($data->documentary_name)?$data->documentary_name:'未维护该客户跟单' ],
            ['最后操作人',$data->reviewer_name,'最后操作时间',$data->review_time],
            ['单据生成时间', $data->created_at,'',''],
        ];

        $table2 = new Table($headers, $rows);
        $content .= $table2->render();

        $content .= '<h4 style="text-align:center;">SKU信息</h4><hr>';

        // table 2
        $headers = [];

        $rows = [
            ['SKU编号',$data->sku_id,'SKU名称', $data->sku_name ],
            ['原始单据',$data->original_id,'皮源编号', $data->cowhide_id ],
            ['等级',$data->batch_grade?$data->batch_grade:"未维护",'厚度',$data->batch_thick?$data->batch_thick:"未维护" ],
            ['产地', $data->batch_origin?$data->batch_origin:"未维护",'颜色',$data->batch_colour?$data->batch_colour:"未维护"],
            ['平均尺寸', $data->batch_avg_size?$data->batch_avg_size:"未维护",'最小尺寸',$data->batch_min_size?$data->batch_min_size:"未维护"],
            ['入库状态', HelpersController::getStateValue('inState',$data->in_state)],

        ];
        $table_3 = new Table($headers, $rows);

        $content .=  $table_3->render();

        $content .= "<h4 style='text-align:center'>备注</h4><hr><p style='background:#efefef;padding:8px;'>".(trim($data->remark)?$data->remark:"无")."</p>";
/* 仓库不允许查看财务状态

        $content .= '<h4 style="text-align:center;">财务状态</h4><hr>';

        //     $table->tinyInteger('invoice')->nullable()->comment('是否开发票');
        //     $table->decimal('invoice_money',11,4)->nullable()->comment('发票费用');

        //     $table->string('remark')->nullable()->comment('备注');
        // table 1

        // if($data->reviewer_id){
            $headers = [];
            $rows = [
                ['支付方式', $data->pay_type==0?"现金":($data->pay_type==1?"电汇":($data->pay_type==2?"支票":($data->pay_type==3?"其它":"未知"))), '支付状态', $data->payment_state==0?"未付款":($data->payment_state==1?"部分付款":($data->payment_state==2?"全款":"未知"))],
                ['订单总价',round($data->total_amount,2)."元","已付款金额",round($data->paid_amount,2)."元"],
                ['财务审核', isset($data->reviewer_name)?$data->reviewer_name:"未审核", "审核时间",isset($data->review_time)?$data->review_time:"未审核"],
            ];
            $table = new Table($headers, $rows);
            $content .=  $table->render();
        // }else{
            // $content .= '<p style="text-align:center;background:#efefef;padding:8px;">尚未维护</p>';
        // }
*/
        $content .= '<h4 style="text-align:center;">仓库设置</h4><hr>';
        $form = new myForm();
        $form->__construct(
            [
                'arrive_time'=>$data->arrive_time,
                'grade'=>$data->grade,
                'thick'=>$data->thick,
                'colour'=>$data->colour,
                'origin'=>$data->origin,
                'avg_size'=>$data->avg_size,
                'min_size'=>$data->min_size,
                'warehouse_id'=>$data->warehouse_id,
                // 'warehouse_zone_id'=>$data->warehouse_zone_id,
                // 'warehouse_location_id'=>$data->warehouse_location_id,
                'sku_name'=>$data->sku_name,
                'in_state'=>$data->in_state,
                'warehouse_name'=>$data->warehouse_name
            ]);
        $form->action($data->id.'/finance');
        $form->method('POST');
        $form->disablePjax();
        $form->hidden('purchase_detail_id')->default($data->id);
        $form->hidden('purchase_id')->default($data->purchase_id);
        $form->hidden('sku_id')->default($data->sku_id);
        $form->hidden('price')->default($data->price);
        $form->hidden('currency')->default($data->currency);
        $form->display('sku_name','SKU');
        $inStateOption = HelpersController::getStateOptions('inState');
        array_shift($inStateOption);
        $form->radio('in_state','入库状态')->options($inStateOption);
        $hadIn = \DB::table('inventory_checking_detail')
            ->where([
                'sku_id'=>$data->sku_id,
                'checking_ASN'=>$data->purchase_id,
                'type'=>2,
                'grade_o' => $data->grade,
                'thick_o' => $data->thick,
                'origin_o' => $data->origin,
                'colour_o' => $data->colour,
                'avg_size_o' => $data->avg_size,
                'min_size_o' => $data->min_size
            ])
            ->select(\DB::raw('sum(size) as size_all'),\DB::raw('sum(num) as num_all'))
            ->first();
        $form->currency('arrive_num','实际入库张数')->symbol("")->help('单据数量： '.$data->num.' ，已入库张数: '.round($hadIn->num_all,2));
        $form->currency('arrive_size','实际入库尺数')->symbol("")->help('单据数量： '.$data->size.' ，已入库尺数: '.round($hadIn->size_all,2));
        $form->select('grade','等级')->options(\DB::table('batchattribute')->where('parent_id','grade')->pluck('name','id'));
        $form->select('thick','厚度')->options(\DB::table('batchattribute')->where('parent_id','thick')->pluck('name','id'));
        $form->select('origin','产地')->options(\DB::table('batchattribute')->where('parent_id','origin')->pluck('name','id'));
        $form->select('colour','颜色')->options(\DB::table('batchattribute')->where('parent_id','colour')->pluck('name','id'));
        $form->select('min_size','最小尺寸')->options(\DB::table('batchattribute')->where('parent_id','min_size')->pluck('name','id'));
        $form->select('avg_size','平均尺寸')->options(\DB::table('batchattribute')->where('parent_id','avg_size')->pluck('name','id'));
        $form->hidden('warehouse_id')->default($data->warehouse_id);
        $form->display('warehouse_name','仓库');
        $form->select('warehouse_zone_id','库区')->options(
            \DB::table('warehouse_zone')
                ->leftjoin('warehouse','warehouse.id','=','warehouse_zone.warehouse_id')
                ->where(['warehouse_id'=>$data->warehouse_id,'warehouse.company_id'=>$data->company_id])
                ->pluck('warehouse_zone.name','warehouse_zone.id')
        )->load('warehouse_location_id', '/admin/helpers/warehouseLocation');
        $form->select('warehouse_location_id','库位')->options(\DB::table('warehouse_location')->pluck('name','id'));

        if($data->review_state == "FINANCE_1ST"){
            if($data->in_state == "ALL_IN"){
                $content.='<p style="text-align:center"> 已全部入库</p>';
            }else{
                $content .= $form->render();
            }
        }elseif($data->review_state == "IN_CHECK"){
            $content.='<p style="text-align:center"> 单据已完成入库</p>';
        }else{
            $content.='<p style="text-align:center">需要等待财务审核通过后操作</p>';
        }
        /*
        $content.='
            <script>
            </script>
        ';
        */
        $items = [
            'header'      => '入库处理',
            'description' => 'Ins',
            'breadcrumb'  => '',
            'content'     => $content."</div>",
        ];

        return view('admin::content', $items)->render();
    }

    public function finance($id){
        $input = \Illuminate\Support\Facades\Input::all();
        $old = \DB::table('purchase')->where('id',$input['purchase_id'])->first();
        if($old->purchase_state == "ALL_IN" ){
            admin_toastr("该SKU已全部入库,如要变更请联系系统管理员",'error');
            return back()->withInput();
        }
        if(!isset($input['in_state'])){
            admin_toastr("入库状态必填","error");
            return back()->withInput();
        }
        if(!$input['warehouse_location_id']){
            admin_toastr("库位必填","error");
            return back()->withInput();
        }
        if(!$input['warehouse_zone_id']){
            admin_toastr("库区必填","error");
            return back()->withInput();
        }
        if(!$input['warehouse_id']){
            admin_toastr("仓库必填","error");
            return back()->withInput();
        }
        if($input['arrive_num']<=0){
            admin_toastr("到货张数至少大于0","error");
            return back()->withInput();
        }
        if($input['price']<=0){
            admin_toastr("未知错误","error");
            return back()->withInput();
        }
        if($input['arrive_size']<=0){
            admin_toastr("到货尺寸至少大于0","error");
            return back()->withInput();
        }
        $old_details = \DB::table('purchase_detail')->where([['id','<>',$id],['purchase_id',$input['purchase_id']]])->get();
        if(count($old_details) > 0){
            if($input['in_state'] == "PART_IN"){
                $operate_state = "PART_IN";
            }else{
                $operate_state = "ALL_IN";
                foreach ($old_details as $old_detail) {
                    if($old_detail->in_state != "ALL_IN"){
                        $operate_state = "PART_IN";
                        break;
                    }
                }
            }
        }else{
            $operate_state = $input['in_state'];
        }
        $update_order_datas['purchase_state'] = $operate_state;

        if($operate_state == "ALL_IN"){
            $update_order_datas['review_state'] = "IN_CHECK";
        }
        $model = new InventoryFunc("purchase",$id);
        try{
            \DB::beginTransaction();

            $model->insertInventoryAndCheckingOne($input);
            \DB::table('purchase')->where(['id'=>$input['purchase_id']])->update($update_order_datas);
            \DB::table('purchase_detail')->where('id',$id)->update(['in_state'=>$input['in_state']]);
            HelpersController::endId('batch_id');
            \DB::commit();
            admin_toastr("入库成功");
            $url = route('ins.index');
            return redirect($url);
        }catch (Exception $e) {
            \DB::rollBack();
            admin_toastr("数据库出错，请联系管理员","error");
            return back()->withInput();
        }
    }
}
